<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="jquery-1.7.2.js"></script>
    <title>jwt-web页面</title>
</head>
<body>
    <form >
        账号<input type="text" name="username"> <br>
        密码<input type="password" name="password"> <br>
        <input type="button" id="login" value="登录"> <br>
    </form>
    <a href="#" id="getWebToken">获取前端传递的token</a>
</body>
<script>
    //登录，保存token到localStorage
    $("#login").click(function(){
    var param = {
     "username": $("input[name=username]").val(),
     "password": $("input[name=password]").val()
    } 
    $.ajax({
      url:"http://127.0.0.1:8080/jwt/login",
      type:'post',
      data:param,
      dataType:"json",
      success:function(res){
        console.log(res)
        if(res.code==400){
          alert("账号或者密码错误");
          return;
        }
        if(res.msg=="账号或者密码为空"){
          alert("账号或者密码为空!");
          return;
        }
        alert("登录成功token="+res.token)
        //保存token到localStorage，方便以后请求鉴权使用
        localStorage.setItem("token",res.token);
      }
    })
})

    //获取登录后每次请求在请求头或者请求参数的token
    $("#getWebToken").click(function(){
    var param = {
     // 使用请求参数传递
     "token":localStorage.getItem("token")
    } 
    $.ajax({
      url:"http://127.0.0.1:8080/jwt/getWebToken",
      type:'post',
      data:param,
      // 使用请求头传递
      beforeSend:function(xhr){
        xhr.setRequestHeader("Authorization",localStorage.getItem("token"))
      },
      dataType:"json",
      success:function(res){
        console.log(res)
      }
    })
    })
    
</script>

</html>